package com.lzh.runke.core.persist.interceptor;

import com.lzh.runke.core.web_base.helper.UUIDHelper;
import com.lzh.runke.core.entity.BaseEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.util.Collection;
import java.util.Date;
import java.util.Properties;
import java.util.Set;

/**
 * mybatis insert方法 拦截器
 * 自动生成ID
 *
 * @author xie
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class})
})
public class BeforeSaveInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];

        Object entityArg = args[1];
        Date date = new Date();
        if (SqlCommandType.INSERT.equals(ms.getSqlCommandType())) {  // 拦截插入记录自动生成ID, delFlag, createDate
            if (entityArg instanceof BaseEntity) { // 单条插入
                BaseEntity entity = (BaseEntity) entityArg;
                if (StringUtils.isBlank(entity.getId())) {
                    entity.setId(UUIDHelper.randomUUID());
                }

                entity.setDelFlag(false);
                entity.setCreateDate(date);
                entity.setUpdateDate(date);
            } else if (entityArg instanceof MapperMethod.ParamMap) {  // 批量插入
                MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap) entityArg;

                Set<String> keySet = paramMap.keySet();
                if (CollectionUtils.isNotEmpty(keySet)
                        && keySet.contains("entities")
                        && null != paramMap.get("entities")) {
                    Collection<BaseEntity> entities = (Collection<BaseEntity>) paramMap.get("entities");
                    for (BaseEntity entity : entities) {
                        if (StringUtils.isBlank(entity.getId())) {
                            entity.setId(UUIDHelper.randomUUID());
                        }
                        entity.setDelFlag(false);
                        entity.setCreateDate(date);
                        entity.setUpdateDate(date);
                    }
                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
